package com.coolsummer.limiter;

import com.coolsummer.abstracts.Limiter;
import com.coolsummer.utils.DateUtil;


/**
 * @author coolsummer
 * @describe 漏桶算法
 * @date 2019/11/18 16:20
 */
public class LeakyBucketLimiter extends Limiter{

    /**
     * 当前时间
     */
    private Long time;

    /**
     * 桶里面的水
     */
    private volatile double water;
    /**
     * 桶的大小
     */
    private double size;

    public LeakyBucketLimiter(double qps) {
        super(qps);
        size = qps;
        water = 0;
        time = DateUtil.getCounterTime();
    }

    /**
     * 漏桶算法实现
     * @return
     */
    @Override
    public synchronized boolean tryAcquire(){
        long current = DateUtil.getCounterTime();
        //出水量
        int out = (int)((current - time) * qps / 1000.0);
        //剩余水量
        water = Math.max(0, water - out);
        time = DateUtil.getCounterTime();
        if(water < size){
            water += 1;
            return true;
        } else {
            return false;
        }
    }
}
